﻿//
// Author: Eldar Radovici
// Email: support@MvcDataTables.NET
// Website: http://MvcDataTables.NET
// Source: http://MvcDataTables.CodePlex.com/
// License: http://MvcDataTables.CodePlex.com/license
// 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web.Mvc;

namespace MvcDataTables
{
    public static class DataTableExtensions
    {
        public static DataTableModel DataTableModel<TController, T>(this HtmlHelper html, Expression<Func<TController, DataTableResult<T>>> getFunction)
        {
            UrlHelper urlHelper = new UrlHelper(html.ViewContext.RequestContext);
            string getAction = getFunction.MethodInfo().Name;
            return new DataTableModel(urlHelper, typeof(TController), typeof(T), getAction);
        }

        //From Harry McIntyre's MVC.JQuery.DataTables
        public static MethodInfo MethodInfo(this Expression method)
        {
            var lambda = method as LambdaExpression;
            if (lambda == null) throw new ArgumentNullException("method");
            MethodCallExpression methodExpr = null;
            if (lambda.Body.NodeType == ExpressionType.Call) methodExpr = lambda.Body as MethodCallExpression;
            if (methodExpr == null) throw new ArgumentNullException("method");
            return methodExpr.Method;
        }

        public static string ToStringOrDefault(this object obj)
        {
            if (obj == null) return String.Empty;
            if (IsEnumerable(obj.GetType()))
            {
                IEnumerable<object> enumerable = ((IEnumerable<object>) obj);
                int count = enumerable.Count();
                return count != 0 ? String.Format("{0} items...", enumerable.Count()) : String.Empty;
            }
            return obj.ToString();
        }

        public static bool IsEnumerable(Type type)
        {
            return typeof(IEnumerable).IsAssignableFrom(type) && type.GetGenericArguments().Length != 0;
        }
    }
}
